package com.toogu.mazhangmen.ui.login;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.toogu.mazhangmen.R;
import com.toogu.mazhangmen.service.DestoryService;
import com.toogu.mazhangmen.service.SockService;
import com.toogu.mazhangmen.ui.main.MainActivity;
import com.toogu.mazhangmen.util.TokenUtil;


public class LoginActivity extends AppCompatActivity implements LoginContract.View , View.OnClickListener {
    private EditText username;
    private EditText password;
    private Button login;
    private CheckBox checkBox;
    private LinearLayout layout;
    private ProgressBar progressBar;

    private SharedPreferences pref;
    private SharedPreferences.Editor editor;

    private LoginPresenter presenter;

    private static String[] PERMISSIONS_STORAGE = {android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.RECORD_AUDIO};
    private static int REQUEST_PERMISSION_CODE=0;

    private long[]mHits=new long[2];//按两次返回退出
    private int time =1000;//1秒内完成

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉状态栏
        setContentView(R.layout.activity_login);
        presenter = new LoginPresenter(this, this);
        startService(new Intent(this, DestoryService.class));
        DestoryService.add(this);
        layout=findViewById(R.id.layout);
        username = findViewById(R.id.username);
        password = findViewById(R.id.password);
        login = findViewById(R.id.login);
        checkBox = findViewById(R.id.check_box);
        progressBar = findViewById(R.id.loading);
        login.setOnClickListener(this);

        pref = PreferenceManager.getDefaultSharedPreferences(this);
        boolean isRemember = pref.getBoolean("remember", false);
        if (isRemember){
            String name = pref.getString("name", "");
            String passwd = pref.getString("passwd", "");
            username.setText(name);
            password.setText(passwd);
            checkBox.setChecked(true);
        }

        for (int i = 0; i < PERMISSIONS_STORAGE.length; i++) {
            if (ActivityCompat.checkSelfPermission(this, PERMISSIONS_STORAGE[i]) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
                return;
            }
        }
        TokenUtil tokenUtil = new TokenUtil();
        if (!tokenUtil.getId().equals("")) {
            presenter.login(tokenUtil.getAccount(), tokenUtil.getPassWord());
        }

    }

    @Override
    protected void onDestroy() {
        DestoryService.remove(this);
        super.onDestroy();
    }


    @Override
    public void onClick(View v) {
        presenter.login(username.getText().toString(),password.getText().toString());
    }

    @Override
    public void showProgressBar() {
        layout.setVisibility(View.INVISIBLE);
        username.setVisibility(View.INVISIBLE);
        password.setVisibility(View.INVISIBLE);
        login.setVisibility(View.INVISIBLE);
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideProgressBar() {
        layout.setVisibility(View.VISIBLE);
        username.setVisibility(View.VISIBLE);
        password.setVisibility(View.VISIBLE);
        login.setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public void onLoginFail(String msg) {
        Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onLoginSuccess() {
        editor = pref.edit();
        if (checkBox.isChecked()) {
            editor.putBoolean("remember", true);
            editor.putString("name", username.getText().toString());
            editor.putString("passwd", password.getText().toString());
        }else {
            editor.clear();
        }
        editor.apply();
        Intent intent = new Intent(this, MainActivity.class);
        startService(new Intent(this, SockService.class));
        startActivity(intent);
        this.finish();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (int grantResult : grantResults) {
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "因拒绝授权，不能使用", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onBackPressed() {
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        if (mHits[0] >= (SystemClock.uptimeMillis() - time)) {
            stopService(new Intent(this, DestoryService.class));
        }else{
            Toast.makeText(getApplicationContext(),"再按一次退出",Toast.LENGTH_SHORT).show();
        }
    }


}
